use derive_builder::Builder;
use serde::{Deserialize, Serialize};

use crate::error::Error;
use crate::mapper::ValueMapper;
use crate::modeling::assistant::FormSchema;
use crate::modeling::workflow::WorkflowEntity;
use crate::modeling::{
    Class, ClassAttributeBuilder, ClassBuilder, ClassGetter, ClassRelationBuilder,
    RelationRelatedType, ValueType,
};
use crate::modeling::{
    ClassAttributePersistence, ClassPersistence, ClassPersistenceBuilder, ClassPersistenceGetter,
    ClassRelation, ClassRelationGetter, Value,
};

const SCHEDULER_TASK_TEMPLATE_CLASS_IDENTIFIER: &'static str = "g01_scheduler_task_template";

const SCHEDULER_TASK_TEMPLATE_CLASS_NAME: &'static str = "scheduler_task_template";

const SCHEDULER_TASK_TEMPLATE_TABLE_NAME: &'static str = "_g01_meta_scheduler_task_templates";

#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub enum SchedulerTaskType {
    /// Workflow
    #[default]
    #[serde(rename = "workflow")]
    Workflow,
}

#[derive(Debug, Default, Serialize, Deserialize, Clone, PartialEq)]
pub enum SchedulerTaskContentType {
    /// Workflow
    #[default]
    #[serde(rename = "workflow")]
    Workflow,
}

#[derive(Debug, Serialize, Deserialize, Default, Clone, Builder, PartialEq)]
#[builder(name = "SchedulerTaskTemplateBuilder")]
#[builder(pattern = "mutable")]
#[builder(setter(into, strip_option), default)]
#[builder(derive(Debug))]
#[builder(build_fn(error = "Error"))]
pub struct SchedulerTaskTemplate {
    /// id
    pub id: i64,
    /// identifier
    pub identifier: String,
    /// 名称
    pub name: String,
    /// 名称
    pub title: String,
    /// 图标
    pub icon: Option<String>,
    /// 类型
    pub task_type: SchedulerTaskType,
    /// 内容类型
    pub content_type: SchedulerTaskContentType,
    /// 内容
    pub content: String,
    /// cron
    pub cron: Option<String>,
    /// variable_schema_identifier
    pub variable_schema_identifier: String,
    /// result_schema_identifier
    pub result_schema_identifier: String,
    /// 选项
    pub options: Option<String>,
    /// 备注
    pub description: String,
    /// 创建时间
    pub created_at: i64,
    /// 更新时间
    pub updated_at: i64,

    pub workflow: Option<WorkflowEntity>,
}

impl ClassGetter for SchedulerTaskTemplate {
    fn get_name() -> anyhow::Result<String> {
        Ok(String::from(SCHEDULER_TASK_TEMPLATE_CLASS_NAME))
    }
    fn get_identifier() -> anyhow::Result<String> {
        Ok(String::from(SCHEDULER_TASK_TEMPLATE_CLASS_IDENTIFIER))
    }
    fn get_class() -> anyhow::Result<Class> {
        let mut attribute_builder = ClassAttributeBuilder::default();
        attribute_builder.class_identifier(SCHEDULER_TASK_TEMPLATE_CLASS_IDENTIFIER);

        let mut commons = crate::modeling::common_attributes_with_builder(&attribute_builder)?;
        let mut append = vec![
            attribute_builder
                .clone()
                .name("task_type")
                .title("类型")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("content_type")
                .title("内容类型")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("content")
                .title("内容")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("variable_schema_identifier")
                .title("变量Schema")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("result_schema_identifier")
                .title("结果Schema")
                .data_type(ValueType::String)
                .build()?,
            attribute_builder
                .clone()
                .name("workflow")
                .title("Workflow")
                .is_persistent(false)
                .data_type(ValueType::Object)
                .build()?,
        ];
        append.append(&mut commons);
        append.sort_by(|a, b| a.position.cmp(&b.position));

        let clazz = ClassBuilder::default()
            .identifier(SCHEDULER_TASK_TEMPLATE_CLASS_IDENTIFIER)
            .name(SCHEDULER_TASK_TEMPLATE_CLASS_NAME)
            .data_is_type(true)
            .is_persistent(true)
            .primary_key(String::from("identifier"))
            .attributes(append)
            .build()?;
        Ok(clazz)
    }
}

//
crate::impl_from_value!(SchedulerTaskTemplate);
crate::impl_class_persistence_getter!(SchedulerTaskTemplate, SCHEDULER_TASK_TEMPLATE_TABLE_NAME);
crate::impl_class_relations_getter!(
    SchedulerTaskTemplate,
    vec![
        ClassRelationBuilder::default()
            .src_identifier(FormSchema::get_identifier()?)
            .target_identifier(Self::get_identifier()?)
            .related_type(RelationRelatedType::Keys)
            .related_at("variable_schema_identifier")
            .build()?,
        ClassRelationBuilder::default()
            .src_identifier(FormSchema::get_identifier()?)
            .target_identifier(Self::get_identifier()?)
            .related_type(RelationRelatedType::Keys)
            .related_at("result_schema_identifier")
            .build()?,
        ClassRelationBuilder::default()
            .src_identifier(WorkflowEntity::get_identifier()?)
            .target_identifier(Self::get_identifier()?)
            .related_type(RelationRelatedType::Keys)
            .related_at("content")
            .build()?
    ]
);
